const jwt = require('../../middleware/jwt/jwt')
// , koajwt = require('koa-jwt');
// 验证函数

// token权限拦截
// app.use(koajwt({
//     secret: 'anlin'
// }).unless({
//     path: [/\/sign/]
// }));


const { User } = require('../../router/schema')
const util = require('../../util/index.js')
module.exports = (app) => {
  app.use(async (ctx, next) => {
    if (ctx.request.url.match('sign')) {
      await next()
    } else if (ctx.request.url.includes('.')) {
      await next()
    } else {
      const  sessionID  = ctx.query.sessionID || ctx.request.body.sessionID
      const token = await jwt.verify(sessionID)
      // 获取到token，然后解析出sessionID和_id
      console.log(token);
      if (token) {
        jwt.sign(token, sessionID, util.tokenTime)
        const yz = async (num) => {
          const _id = token;
          await User.findOne({ _id }).then(async res => {
            if (res) {
              if (res.role === num) {
                await next()
              } else {
                ctx.body = {
                  code: -201,
                  data: null,
                  msg: 'role权限不足'
                }
              }
            } else {
              ctx.body = {
                code: -401,
                data: null,
                msg: 'token失效'
              }
            }
          })
        }

        if (ctx.request.url.match('admin')) {
          await yz(100)
        } else {
          await yz(10)
        }
      } else {
        ctx.body = {
          code: -201,
          data: null,
          msg: 'token验证失败'
        }
      }
    }
  })
}